package com.control.back.halo.bookmark.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.control.back.halo.basic.dao.IBaseDao;
import com.control.back.halo.basic.entity.vo.TreeNode;
import com.control.back.halo.basic.log4j.Logger;
import com.control.back.halo.basic.service.impl.BaseServiceImpl;
import com.control.back.halo.basic.utils.UserUtils;
import com.control.back.halo.bookmark.dao.ICategoryDao;
import com.control.back.halo.bookmark.dao.IMarkDao;
import com.control.back.halo.bookmark.entity.Category;
import com.control.back.halo.bookmark.entity.Mark;
import com.control.back.halo.bookmark.service.ICategoryService;

@Service("categoryService")
public class CategoryServiceImpl extends BaseServiceImpl<Category, Long> implements ICategoryService {

    private static Logger logger = Logger.getLogger(CategoryServiceImpl.class);

    @Resource(name = "categoryDaoImpl")
    ICategoryDao          categoryDao;

    @Resource(name = "markDaoImpl")
    IMarkDao              markDao;

    @Override
    public IBaseDao<Category, Long> getBaseDao() {
        return this.categoryDao;
    }

    public List<Category> findAll() {
        List<Category> array = categoryDao.findAllByAuth(UserUtils.getCurrentUser());
        if (array == null) { return null; }
        return array;
//        return super.findAll();
    }

    public Category update(Category category) {
        return super.update(category);
    }

    @Override
    public List<TreeNode> loadCategoryTree() {
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();

        List<Category> categorys = findAll();
        if (categorys != null && !categorys.isEmpty()) {
            for (Category category : categorys) {
                TreeNode t = new TreeNode();
                t.setId(category.getId());
                t.setName(category.getTitle());
                t.setParent(category.getChildren() != null);
                t.setPid(category.getParent() != null ? category.getParent().getId() : 0);
                treeNodes.add(t);
            }
        }

        return treeNodes;
    }

    @Override
    public Map<String, List<Category>> findRepeatCategory() {

        Map<String, List<Category>> cm = new HashMap<String, List<Category>>();
       List<Category> catgorys = categoryDao.findRepeatCategory(UserUtils.getCurrentUser().getId());
       // List<Category> catgorys = categoryDao.findAll();
        if (catgorys != null) {
            for (Category category : catgorys) {
                List<Category> tcs = cm.get("T" + category.getTitleHashCode());
                if (tcs == null) {
                    tcs = new ArrayList<>();
                }
                tcs.add(category);
                cm.put("T" + category.getTitleHashCode(), tcs);
            }
        }
        return cm;
    }

    @Transactional
    @Override
    public boolean mergeCategory(Long mId, String cIds) {

        logger.debug("merge category params :{mid:%s,cIds:%s}", mId, cIds);

        try {
            Category parent = categoryDao.findOne(mId);
            List<Long> idLongs = new ArrayList<Long>();
            if (!StringUtils.isEmpty(cIds)) {
                String[] ids = cIds.split(",");
                for (String idStr : ids) {
                    if (StringUtils.isNotBlank(idStr)) {
                        Long idLong = Long.parseLong(idStr);
                        idLongs.add(idLong);
                    }
                }
            }

            List<Category> categorys = categoryDao.findByParentIds(idLongs);
            if (categorys != null) {
                for (Category category : categorys) {
                    category.setParent(parent);
                    categoryDao.save(category);
                }
            }

            List<Mark> marks = markDao.findByCategoryIds(idLongs);
            if (marks != null) {
                for (Mark mark : marks) {
                    mark.setCategory(parent);
                    markDao.save(mark);
                }
            }

            this.deleteByIds(idLongs.toArray(new Long[idLongs.size()]));
        } catch (Exception e) {
            logger.error("merge category error", e);
            return false;
        }

        return true;
    }

    @Override
    public List<Category> findCategoryByIds(String ids) {
        List<Long> idLongs = new ArrayList<Long>();
        if (!StringUtils.isEmpty(ids)) {
            String[] idArray = ids.split(",");
            for (String idStr : idArray) {
                if (StringUtils.isNotBlank(idStr)) {
                    Long idLong = Long.parseLong(idStr);
                    idLongs.add(idLong);
                }
            }
        }
        return categoryDao.findByIds(idLongs);
    }

    @Override
    public List<Category> findCategoryByName(String name) {
        return categoryDao.findCategoryByName("%" + name + "%");
    }

}
